package cn.mifengkong.appcommon.util;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

import com.mifengkong.frtools.util.FRToast;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;


/**
 * Created by jiangyongxing on 2017/8/22.
 * 描述：
 */

public class ActivityStartUtil {


    private static List<Class> mClazzList;


    /**
     * 根据Activity的名称和参数开启对应的页面
     *
     * @param context
     * @param activityName
     * @param parameter
     * @param applicationId
     */
    public static void startActivityByActivityNameAndParameter(Context context, String activityName, String parameter, String applicationId) {
        startActivityByActivityNameAndParameter(context, activityName, parameter, applicationId, null);
    }

    /**
     * 根据Activity的名称和参数开启对应的页面
     *
     * @param context
     * @param activityName
     * @param parameter
     * @param applicationId
     */
    public static void startActivityByActivityNameAndParameter(Context context, String activityName, String parameter, String applicationId, StartActivityResultListener listener) {
        //这里是因为h5调用的Activity的名字并不是我们Activity的名字 所以要去配置文件里面找出来我们配好的Activity 和 给特定的Activity 的配置的参数
        String startActivityName = getStartActivity(context, activityName);
        if (TextUtils.isEmpty(parameter)) {
            parameter = getStartActivityParams(context, activityName);
        }
        Bundle bundle = new Bundle();
        //分割参数
        bundle = splitParameter(parameter, bundle);
        try {
            Intent intent = new Intent();
            intent.putExtras(bundle);
            intent.setClass(context, getClassbyName(context, startActivityName, applicationId));
            context.startActivity(intent);
        } catch (Exception e) {
            if (listener != null) {
                listener.failure();
            }
        }
        if (listener != null) {
            listener.success();
        }
    }

    /**
     * 根据JS调用的activityName返回本地的Activity的名称
     *
     * @param context
     * @param activityName
     * @return 如果有配置返回配置项 没有的话返回原输入项
     */
    private static String getStartActivity(Context context, String activityName) {
        Properties properties = new Properties();
        try {
            properties.load(context.getAssets().open("activity.properties"));
            String cardManagerHome = properties.getProperty(activityName);
            if (!TextUtils.isEmpty(cardManagerHome)) {
                return cardManagerHome;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return activityName;
    }

    /**
     * 如果有配置的话返回对应的Activity参数配置
     *
     * @param context
     * @param activityName
     * @return 如果有相应的配置就返回  没有就返回null
     */
    private static String getStartActivityParams(Context context, String activityName) {
        Properties properties = new Properties();
        String cardManagerHome = "";
        try {
            properties.load(context.getAssets().open("params.properties"));
            cardManagerHome = properties.getProperty(activityName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return cardManagerHome;
    }

    /**
     * 分割参数，将uid=12&token=36进行分割
     *
     * @param parameter
     * @param bundle
     */
    private static Bundle splitParameter(String parameter, Bundle bundle) {
        if (!TextUtils.isEmpty(parameter)) {
            String[] parameters = parameter.split("&");
            for (String s : parameters) {
                String[] map = s.split("=");
                if (!TextUtils.isEmpty(map[0]) && !TextUtils.isEmpty(map[1])) {
                    bundle.putString(map[0], map[1]);
                }
            }
        }

        return bundle;
    }

    /**
     * 分割参数，将uid=12&token=36进行分割
     *
     * @param parameter
     * @return 返回一个json
     */
    public static JSONObject splitParameter(String parameter) {
        JSONObject jsonObject = new JSONObject();
        if (!TextUtils.isEmpty(parameter)) {
            String[] parameters = parameter.split("&");
            for (String s : parameters) {
                String[] map = s.split("=");
                if (map.length > 1) {//正常情况  a=b
                    if (!TextUtils.isEmpty(map[0]) && !TextUtils.isEmpty(map[1])) {
                        try {
                            jsonObject.put(map[0], map[1]);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                } else if (map.length == 1) {//不正常的时候  a=
                    if (!TextUtils.isEmpty(map[0])) {
                        try {
                            jsonObject.put(map[0], "");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return jsonObject;
    }

    /**
     * 根据Activity 的名字返回对应activity的Class
     *
     * @param context
     * @param activityName
     */
    private static Class getClassbyName(Context context, String activityName, String applicationId) {
        Class mCurrentActivityClass = null;
        initClazzList(context, applicationId);
        if (TextUtils.isEmpty(activityName)) {
            return mCurrentActivityClass;
        }
        for (Class aClass : mClazzList) {
            String aClassNameLong = aClass.toString();
            if (!aClassNameLong.contains(applicationId)) {
                //只跳转app中定义的Activity，其他module中忽略
                continue;
            }
            String[] aClassNames = aClassNameLong.split("\\.");
            if (aClassNames == null || aClassNames.length == 0) {
                continue;
            }
            String aClassName = aClassNames[aClassNames.length - 1];
            if (activityName.equals(aClassName)) {
                mCurrentActivityClass = aClass;
                break;
            }
        }
        return mCurrentActivityClass;
    }

    /**
     * 该方法比较耗时
     *
     * @param context
     * @param applicationId
     */
    private static void initClazzList(Context context, String applicationId) {
        if (mClazzList == null) {
            mClazzList = ClassUtil.getActivitiesClass(context, applicationId);
        }
    }

    /**
     * 根据Url启动Activity
     *
     * @param url
     */
    public static void launch(Context context, String pageName, String url) {
        String launchActivity = getLaunchActivity(url);
        Map<String, String> launchActivityParams = getLaunchActivityParams(url);
        if (!TextUtils.isEmpty(launchActivity)) {
            Class aClass = ClassUtil.getClassByName(context, pageName, launchActivity);
            if (null != aClass) {
                Intent paramsIntent = getParamsIntent(aClass, context, launchActivityParams);
                context.startActivity(paramsIntent);
            }
        }
    }

    /**
     * @param aClass               要启动的Activity的类对象
     * @param launchActivityParams 要启动的Activity的启动参数
     * @return Intent
     */
    public static Intent getParamsIntent(Class aClass, Context context, Map<String, String> launchActivityParams) {
        Intent intent = new Intent(context, aClass);
        if (launchActivityParams.size() != 0) {
            Set<String> keySet = launchActivityParams.keySet();
            Iterator<String> iterator = keySet.iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                String value = launchActivityParams.get(key);
                intent.putExtra(key, value);
            }
        }
        return intent;
    }

    /**
     * @param url 请求的URl
     * @return 返回要启动的Activity
     * kamao://LaunchActivity?userId=1&user=110
     */
    public static String getLaunchActivity(String url) {
        String[] split = url.split("kamao://");
        if (split.length == 1) {
            return "";
        }
        String param = split[1];
        String[] splitEnd = param.split("\\?");
        String activity = splitEnd[0];
        return activity;
    }

    /**
     * @param url 请求的URL
     * @return 返回参数数组
     * kamao://LaunchActivity?userId=1&user=110
     */
    public static Map<String, String> getLaunchActivityParams(String url) {
        Map launchParams = new HashMap();
        String[] split = url.split("kamao://");
        String param = split[1];
        String[] splitEnd = param.split("\\?");
        //并没有包含参数
        if (splitEnd.length == 1) {
            return new HashMap<>();
        }
        String param2 = splitEnd[1];
        String[] params3 = param2.split("&");
        for (int i = 0; i < params3.length; i++) {
            String s2 = params3[i];
            String[] split2 = s2.split("=");
            String s3 = split2[0];
            String s4 = split2[1];
            launchParams.put(s3, s4);
        }
        return launchParams;
    }


    /**
     * 手机上是否安装有微信
     *
     * @param context
     * @return
     */
    public static boolean OpenWeinxinAviliable(Context context) {
        final PackageManager packageManager = context.getPackageManager();// 获取packagemanager
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);// 获取所有已安装程序的包信息
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                if (pn.equals("com.tencent.mm")) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 开启微信
     *
     * @param context
     */
    public static void startWeiXin(Context context) {
        if (OpenWeinxinAviliable(context)) {
            Intent intent = new Intent();
            ComponentName cmp = new ComponentName("com.tencent.mm", "com.tencent.mm.ui.LauncherUI");
            intent.setAction(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(cmp);
            context.startActivity(intent);
            return;
        }
        FRToast.showToastSafe("请先安装微信");

    }
}
